package com.digital.library.modules.system.controller;

import com.digital.library.common.config.LoginConfig;
import com.digital.library.common.constant.CommonConstant;
import com.digital.library.common.utils.*;
import com.digital.library.common.vo.Result;
import com.digital.library.common.vo.Token;
import com.digital.library.modules.system.domain.SysUser;
import com.digital.library.modules.system.service.SysUserService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * 系统登录/退出控制类
 */
@RestController
public class LoginController {

    @Autowired
    SysUserService sysUserService;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginConfig loginConfig;

    /**
     * 用户登录
     * @param sysUser
     * @return
     */
    @ApiOperation("登录接口")
    @PostMapping(value = "/login")
    public Result<?> login(@RequestBody SysUser sysUser, HttpServletRequest request) {

        // 验证ip地址和用户登录是否已受限
        String ip = IPUtil.getIpAddr(request);
        String redisKeyLimit=String.format("%s_%s_login_limit", ip, sysUser.getName());
        if(redisUtil.get(redisKeyLimit)!=null){
            return Result.error(String.format("错误次数太频繁，请 %s 分钟后再重试",loginConfig.getLimitMinute()));
        }


        //校验用户是否存在
        SysUser user = sysUserService.authUser(sysUser);
        if(user == null){
            //计算错误次数
            String redisKeyErrorTimes=String.format("%s_%s_login_error", ip, sysUser.getName());//错误次数的key
            Integer errorTimes=0;
            Object error=redisUtil.get(redisKeyErrorTimes);
            if(error!=null)
            {
                errorTimes=ObjectConvertUtil.getInt(error);
            }
            errorTimes += 1;
            redisUtil.set(redisKeyErrorTimes,errorTimes, 24*60*60);
            if(errorTimes>=loginConfig.getErrorTimes()){
                redisUtil.set(redisKeyLimit,1,loginConfig.getLimitMinute()*60);
            }
            return Result.error("用户密码不正确，请重新输入！");
        }

        //生成Token
        String token = JwtUtil.sign(user.getName(), user.getPassword());

        //Token暂存redis(10分钟)，用于服务请求认证
        String key = CommonConstant.PREFIX_USER_TOKEN+sysUser.getName();
        redisUtil.set(key, user, 10*60);
        Token tokenVO = new Token();
        tokenVO.setName(sysUser.getName());
        tokenVO.setToken(token);
        tokenVO.setTimeout(DateUtil.AddMin(new Date(), 10));

        return Result.ok(tokenVO);
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @ApiOperation("退出登录接口")
    @GetMapping(value = "/logout")
    public Result<Object> logout(HttpServletRequest request, HttpServletResponse response) {
        //用户退出逻辑
        String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String name = JwtUtil.getUsername(token);
        if(!ObjectConvertUtil.isEmpty(token)) {
            //清空用户登录Token缓存
            redisUtil.del(CommonConstant.PREFIX_USER_TOKEN + name);

        }
        return Result.ok("退出登录成功！");
    }

}
